package NGUYENVANDOAN.SERIZABLEFILES;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MODELS {
    /***
     * Nghiệp vụ ghi dữ liệu Object xuống files
     * 
     * @param lisStudent
     * @param resource 
     *            - Sample: abc/files/
     * @param fileName
     *            - Sample: abcd.dat
     * @return
     * @throws IOException
     */
    public boolean WriteListObjectIntoFiles(List<Student> lisStudent,
                                    String resource, String fileName) throws Exception {
        try {            
            String path = resource + "/" + fileName;
            File objFile = new File(path);
            
            FileOutputStream objOutFile = new FileOutputStream(objFile);
            ObjectOutputStream objOoS = new ObjectOutputStream(objOutFile);
            objOoS.writeObject(lisStudent);
            objOoS.flush();                  
        } catch (Exception e) {
            throw e;
        }
        return true;
    }

    /***
     * Nghiệp vụ đọc dữ liệu từ files --> List Object trong Java
     * @param resource - Sample: abc/files/
     * @param fileName - Sample: abcd.dat
     * @return
     * @throws Exception
     */
    public List<Student> ReadListObjectIntoFiles(String resource, String fileName) 
                                    throws Exception {
        List<Student> lisStudent = null;
        try {            
            String path = resource + "/" + fileName;
            File objFile = new File(path);
            ObjectInputStream objObjectIn = new ObjectInputStream(new 
                    FileInputStream(objFile));
            lisStudent = new ArrayList<Student>();
            lisStudent = (List<Student>)objObjectIn.readObject();      
        } catch (Exception e) {
            throw e;
        }
        return lisStudent;
    }
}
